package com.li.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import com.li.exception.BaseException;
import com.li.mapper.UserMapper;
import com.li.pojo.dto.LoginDto;
import com.li.pojo.po.User;
import com.li.pojo.vo.CaptchaImageVo;
import com.li.pojo.vo.LoginVo;
import com.li.properties.JwtProperties;
import com.li.utile.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

//登录
@RestController
public class loginController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserMapper userMapper;


    @PostMapping("logout")
    public String logout(){
        return "{\"msg\":\"退出成功\",\"code\":200}";
    }

    @CrossOrigin("*")
    @GetMapping("getInfo")
    public String getInfo(){
        return "{\n" +
                "    \"msg\": \"操作成功\",\n" +
                "    \"code\": 200,\n" +
                "    \"permissions\": [\n" +
                "        \"*:*:*\"\n" +
                "    ],\n" +
                "    \"roles\": [\n" +
                "        \"admin\"\n" +
                "    ],\n" +
                "    \"user\": {\n" +
                "        \"createBy\": \"admin\",\n" +
                "        \"createTime\": \"2021-03-31 03:12:10\",\n" +
                "        \"updateBy\": null,\n" +
                "        \"updateTime\": null,\n" +
                "        \"userId\": 1,\n" +
                "        \"deptId\": 103,\n" +
                "        \"userName\": \"admin\",\n" +
                "        \"nickName\": \"admin\",\n" +
                "        \"email\": \"admin@163.com\",\n" +
                "        \"phonenumber\": \"15888888888\",\n" +
                "        \"sex\": \"1\",\n" +
                "        \"avatar\": \"\",\n" +
                "        \"salt\": null,\n" +
                "        \"status\": \"0\",\n" +
                "        \"delFlag\": \"0\",\n" +
                "        \"loginIp\": \"127.0.0.1\",\n" +
                "        \"loginDate\": \"2021-03-31T03:12:10.000+0800\",\n" +
                "        \"dept\": {\n" +
                "            \"createBy\": null,\n" +
                "            \"createTime\": null,\n" +
                "            \"updateBy\": null,\n" +
                "            \"updateTime\": null,\n" +
                "            \"deptId\": 103,\n" +
                "            \"parentId\": 101,\n" +
                "            \"ancestors\": null,\n" +
                "            \"deptName\": \"研发部门\",\n" +
                "            \"orderNum\": \"1\",\n" +
                "            \"leader\": \"若依\",\n" +
                "            \"phone\": null,\n" +
                "            \"email\": null,\n" +
                "            \"status\": \"0\",\n" +
                "            \"delFlag\": null,\n" +
                "            \"parentName\": null,\n" +
                "            \"users\": [],\n" +
                "            \"children\": []\n" +
                "        },\n" +
                "        \"roles\": [\n" +
                "            {\n" +
                "                \"createBy\": null,\n" +
                "                \"createTime\": null,\n" +
                "                \"updateBy\": null,\n" +
                "                \"updateTime\": null,\n" +
                "                \"roleId\": 1,\n" +
                "                \"roleName\": \"超级管理员\",\n" +
                "                \"roleKey\": \"admin\",\n" +
                "                \"roleSort\": \"1\",\n" +
                "                \"dataScope\": \"1\",\n" +
                "                \"menuCheckStrictly\": false,\n" +
                "                \"deptCheckStrictly\": false,\n" +
                "                \"status\": \"0\",\n" +
                "                \"delFlag\": null,\n" +
                "                \"flag\": false,\n" +
                "                \"menuIds\": null,\n" +
                "                \"deptIds\": null,\n" +
                "                \"admin\": true\n" +
                "            }\n" +
                "        ],\n" +
                "        \"roleIds\": null,\n" +
                "        \"admin\": true\n" +
                "    }\n" +
                "}";
    }

//    @GetMapping("captchaImage")
//    public String captchaImage(){
//        return "{\n" +
//                "    \"msg\": \"操作成功\",\n" +
//                "    \"img\": \"/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyM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JLjyVMiZCuV5UHrg1OGzBxryrYle05k7pt69vu7bWBw0stDq9B2vYROqMu5QdrDBGexHrW0Ky9KgaGBVatUV5pY4VV1f/kCX/wD17Sf+gmrYqrq//IEv/wDr2k/9BNTL4WTL4WclZf8AHlb/APXNf5VZFczFrVzFEkapEQihRkHt+NSf2/df884f++T/AI1lGtGyM41Y2R0ooMYYYIrm/wDhIbv/AJ5wf98n/Gl/4SK7/wCecH/fJ/xqvbRH7aJ0C2ke7O0VYSNV6CuY/wCEkvP+eUH/AHyf8aX/AISW8/55Qf8AfJ/xo9tEPbROsAo8tT1Fcp/wk97/AM8rf/vlv8aX/hKL3/nlb/8AfLf40e2iHtonXKgAoMKt1Arkv+Eqvv8Anlb/APfLf40v/CV33/PK2/75b/Gj20Q9tE6j7BETnaKsRW6RjgCuQ/4S2/8A+eNt/wB8t/jS/wDCX6h/zxtv++W/+Ko9tEPbRO2UAU8CuH/4TDUP+eNr/wB8t/8AFUv/AAmWo/8APG1/75b/AOKo9tEPbRO5wDSeQhOSBXEf8JnqP/PG1/74b/4ql/4TXUv+eFp/3w3/AMVR7aIe2id4iBRxUgrgP+E21L/nhaf98N/8VS/8Jxqf/PC0/wC+G/8AiqPbRD20T0EVV1f/AJAeof8AXtJ/6Ca4r/hOdT/54Wn/AHw3/wAVUdz4z1G6tZrd4bUJKjIxVWyARjj5qmVaNmKVWNmf/9k=\",\n" +
//                "    \"code\": 200,\n" +
//                "    \"uuid\": \"79c8dcb25c1243058bf94a7e7e0976c4\"\n" +
//                "}";
//    }
//

    @GetMapping("/captchaImage")
    public CaptchaImageVo captchaImage() throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        //设置长宽高
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        // 自定义验证码内容为四则运算方式
        lineCaptcha.setGenerator(new MathGenerator(1));
        lineCaptcha.write(out);
        //生成uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        out.close();
        //redis储存
        String code = lineCaptcha.getCode();
        redisTemplate.opsForValue().set(uuid,code,5L, TimeUnit.MINUTES);

//        boolean verify = new MathGenerator().verify(code, "23"); 校验方法
        return new CaptchaImageVo("验证码返回成功",out.toByteArray(),200,uuid);
    }

//    @CrossOrigin("*")
//    @PostMapping("login")
//    public String login(){
//        return "{\n" +
//                "    \"msg\": \"操作成功\",\n" +
//                "    \"code\": 200,\n" +
//                "    \"token\": \"eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjEyNDk2ZDRlLTQwOWItNDJhNC05NWZjLTBhNzNmNmE0OTlmNCJ9.s4BLGDE0VVdPZmIwxw35LuOuZLi9wvEkjZiWV_TkbVeyMyVfLdBzye1UXpG8Tz-fDN7SoM1KM60p4v85gETJRw\"\n" +
//                "}";
//    }

    @PostMapping("login")
    public LoginVo login(@RequestBody LoginDto loginDto){
        Object code = redisTemplate.opsForValue().get(loginDto.getUuid());
        if (code==null){
            throw new BaseException("验证码已过期");
        }else if (!new MathGenerator().verify((String) code,loginDto.getCode())){
            throw new BaseException("验证码错误");
        }
        User user =userMapper.selectByUsername(loginDto.getUsername());
        if (user==null){
            throw new BaseException("用户名不存在");
        }else if (!user.getPassword().equals(loginDto.getPassword())){
            throw new BaseException("密码错误");
        }

        //登入成功,生成token
        HashMap<String,Object> claims=new HashMap<>();
        claims.put("id",user.getUserId());
        claims.put("name",user.getUserName());
        String token = JwtUtil.createJWT(jwtProperties.getSecretKey(), jwtProperties.getTtl(), claims);
        return new LoginVo("操作成功",200,token);
    }
}
